<?php

namespace app\stores\controller\miniapp\member;

use app\BaseController;
use app\beautiful\model\LevelModel;
use app\beautiful\model\logs\MemberBalanceLogsModel;
use app\beautiful\model\member\MemberBalanceModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberIntegralModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\PartnerModel;
use app\beautiful\model\setting\LevelSettingModel;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\StaffModel;
use app\common\helper\open\OpenPlatformBaseHelper;
use app\common\helper\open\OpenPlatformMiniappHelper;
use app\common\logic\DataLogic;
use app\common\model\MemberMoneyDetailModel;
use app\common\model\ShopDetailModel;
use app\common\model\ShopModel;
use app\stores\model\logs\MemberPlatfromMoneyLogsModel;
use app\stores\model\member\MemberLevelModel;
use app\stores\model\member\WhiteListModel;
use app\stores\model\promotion\PromotionmemberModel;

class Member extends BaseController{
    //获取用户是否还是员工 和 分销员等 包括后期的是否是教练等 获取用户是否在该门店白名单

    public function getMemberRole(){

        $member=$this->request->member;

        $shopStaff = StaffModel::where([

            ['mobile','=',$member->mobile],

            ['status','=',1],

            ['is_delete','=',0]

        ])->find();

        $is_staff = $shopStaff===null ? 0 : 1;



        $partner = PartnerModel::where([

            //['shop_id','=',$this->request->shopId],

            ['member_id','=',$member->member_id],

            ['status','=',1],

            ['is_delete','=',0]

        ])->find();

        $is_partner =  $partner === null ? 0 : 1;

        $partner_role = $partner === null ? 0 : $partner->role_id;

        $lead_member = PromotionmemberModel::info(['is_effect'=>1,'is_delete'=>0,'member_id'=>$member->member_id,'type'=>2],['id'=>'asc']);

        $promotion = PromotionmemberModel::info(['is_effect'=>1,'is_delete'=>0,'member_id'=>$member->member_id]);

        return $this->success([

            'info' =>[

                'shop_id' => empty($is_staff)?35:$shopStaff->shop_id,

                'is_staff'      => $is_staff,

                'is_partner'    => $is_partner,

                'partner_role'  => $partner_role,

                'is_team_lead'  =>empty($lead_member)?0:1,

                'is_promotion'=>empty($promotion)?0:1,
            ],

        ]);

    }


    public function show()

    {

        $member=$this->request->member;

        $shop_id = $this->request->param('shop_id/d',0);

        $member->append(['hidden_mobile','birthday']);

        $balance = MemberBalanceModel::where([

                ['shop_id','=',$shop_id],

                ['member_id','=',$member->member_id],

                ['valid_bg_time','<=',$this->request->time()]

            ])->sum('remain_balance') ?? 0;

        $frozen_balance=MemberBalanceModel::where([

                ['shop_id','=',$shop_id],

                ['member_id','=',$member->member_id],

                ['valid_bg_time','>',$this->request->time()]

            ])->sum('remain_balance') ?? 0;;





        $integral = MemberIntegralModel::where([

                ['shop_id','=',$shop_id],

                ['member_id','=',$member->member_id],

                ['expire_time','>',$this->request->time()]

            ])->sum('remain_integral') ?? 0;



        $coupon_count = MemberCouponModel::where([
                ['status','=',0],
                ['valid_end_time','>=',date('Y-m-d', $this->request->time())],
                ['member_id','=',$member->member_id],
            ])->count() ?? 0;

        $shopDetail = ShopDetailModel::find($shop_id);

        $is_member = $shopDetail['is_member'];//会员推荐
        $is_valid_member = 0;//是否为有效用户（在门店有效期的白名单内）

        if($member->white_list_shop){
            $white_list_shop_arr = json_decode($member->white_list_shop,true);

            $shop_id_arr = array_column($white_list_shop_arr, 'shop_id');

            $key = array_search($shop_id, $shop_id_arr);

            if($key!==false){
                if($white_list_shop_arr[$key]['in_white_list']>0 && time()>=strtotime($white_list_shop_arr[$key]['start_time']) && time()<=strtotime($white_list_shop_arr[$key]['end_time'])) {
                    $is_valid_member = 1;
                }
            }
        }
        //待解冻
        $detail_model = new MemberMoneyDetailModel();
        $d_list= $detail_model->getList([],['money_status'=>0,'member_id'=>$this->request->memberId],'');
        $wait_money = $d_list['income_money'];
        //是否是门店会员（除开基础会员）
        $is_buy_member = isBuyMember($this->request->memberId,$shop_id);

        $return=[

            'member_info'=>[
                'is_buy_member' =>$is_buy_member,

                'member_id' => sprintf("%08d", $member->member_id),

                'member_num'=>$member->member_num,

                'money'=>$member->money<0?0:$member->money,

                'wait_money'=>$wait_money,

                'nick_name'=>$member->nick_name,

                'birthday' => $member->birthday,

                'sex'       => $member->sex,

                'face'=>$member->face,

                'level_id'=>$member->level_id,

                'level_name'=>$member->level ? $member->level->name : '普通会员',

                'balance'=>$balance,

                'frozen_balance'=>$frozen_balance,

                'total_balance' =>round(($balance *  100  + $frozen_balance * 100)/100,2),

                'integral'=>$integral,

                'coupon_count'=>$coupon_count,

                'hidden_mobile'=>$member->hidden_mobile,

                'white_list_open' =>(null === $shopDetail)?0:$shopDetail->white_list_open,

                'is_valid_member' =>$is_valid_member,
                'is_member' =>$is_member,
                'mobile' =>$member->mobile,

            ]


        ];

        return $this->success($return);

    }

    public function saveMemberInfo()

    {

        $nick_name = $this->request->param('nick_name');

        $sex = $this->request->param('sex/d',0);

        $birthday = $this->request->param('birthday');

        $face = $this->request->param('face');

        $mobile = $this->request->param('mobile');

        if(empty($nick_name) || mb_strlen($nick_name) >32) return $this->error('请输入昵称且昵称长度不能多余32');

        if(!in_array($sex,[0,1,2])) return $this->error('请选择性别');

//        if(empty($birthday)) return $this->error('请选择生日');

        if($birthday && (false === strtotime($birthday." 00:00:00"))) return $this->error('请选择正确的生日');

        if($birthday) $birthday_arr=explode('-',$birthday);

        if($birthday && count($birthday_arr) !=3) return $this->error('请选择正确的生日');

        if($birthday){
            $birthday_year=$birthday_arr[0]; $birthday_month=$birthday_arr[1]; $birthday_day=$birthday_arr[2];
        }

//        if((mb_strlen($birthday_year) !=4) || (mb_strlen($birthday_month) !=2) (mb_strlen($birthday_day) !=2)) return $this->error('请选择正确的生日');



        $member=$this->request->member;

        $member->nick_name=$nick_name;

        $member->sex=$sex;

        if($birthday) {

            $member->birthday_year = $birthday_year;

            $member->birthday_month = $birthday_month;

            $member->birthday_day = $birthday_day;
        }

        if(!empty($face)){

            $member->face = $face;

        }
        if(!empty($mobile)) $member->mobile = $mobile;

        $member->save();



        return $this->success("修改成功");

    }

    public function saveMemberFace()

    {

        $face = $this->request->param('face');
        if(empty($face)) return $this->error('请上传头像');

        $member=$this->request->member;
        $member->face = $face;
        $member->save();

        return $this->success("修改成功");

    }

    //获取用户的Qrcode
    public function getMemberQrcode(){

        $member = $this->request->member;

        $code=rand(111111,999999);

        $member->code=$code;

        $member->save();

        return $this->success([
            'nick_name'=>$member->nick_name,

            'face'=>$member->face,

            'member_id'=>sprintf("%08d", $member->member_id),

            'member_num'=>$member->member_num,

            'code'=>$code

        ]);

    }
    //获取会员卡
    public function getMemberCard(){
        $member_model = new MemberLevelModel();
        //存在的门店
        $shop_ids = ShopModel::where(['open_status'=>1])->column('shop_id');
        $where['shop_ids'] = $shop_ids;
        $where['member_id'] = $this->request->memberId;
        $return = $member_model->getList($where,['ml.add_time'=>'asc'],$this->request->page,$this->request->limit);
        return $this->success($return);
    }
    /*门店会员中心*/
    public function shopMemberInfo(){
        $shop_id = $this->request->shopId;

        $level_setting = LevelSettingModel::where(['is_selected'=>1,'shop_id'=>$shop_id])->find();
        $type = $level_setting->type;

//        $member = MemberModel::with(['memberlevel'=>function($query)use($shop_id,$type){
//            $query->where(['shop_id'=>$shop_id,'is_delete'=>0,'type'=>$type]);
//        }])->field('member_id,member_num,nick_name,face,code,mobile')
//            ->where(['member_id'=>$this->request->memberId,'is_delete'=>0])
//            ->find();
        $member = MemberModel::info(['member_id'=>$this->request->memberId,'shop_id'=>$shop_id,'type'=>$type],'m.member_id,m.member_num,m.nick_name,m.face,m.code,m.mobile,ml.shop_id,ml.level_id');

        if(empty($member))  return $this->error('会员不存在');

        //$member = $member->toArray();

        //会员等级
//        if($member['memberlevel']['level_id']){
//            $level_model = new LevelModel();
//            $level = $level_model->getById(['level_id'=>$member['memberlevel']['level_id'],'is_delete'=>0]);
//            $member['level_name'] = $level['name'];
//        }else{
//            $member['level_name'] = '普通会员';
//        }


        $member_balance_model = new MemberBalanceModel();
        $return = $member_balance_model->getBalanceSumByMemberId(['member_id'=>$this->request->memberId],1,$this->request->shopId);
        $member['balance'] = $return?$return[$this->request->memberId]:0;
        $shop = ShopModel::where(['shop_id'=>$this->request->shopId])->find();
        $member['shop_name'] = $shop->name;
        //卡项
        $member['card_num'] = 0;
        //优惠券
        $member['coupon_num'] = MemberCouponModel::where(['shop_id'=>$this->request->shopId,'member_id'=>$this->request->memberId,'status'=>0])->count();
        $member['member_id'] = sprintf("%08d", $this->request->memberId);

        $shopStaff = StaffModel::where([
            ['shop_id','=',$this->request->shopId],
            ['mobile','=',$member['mobile']],
            ['status','=',1],
            ['is_delete','=',0]
        ])->find();

        $member['is_staff'] = $shopStaff===null ? 0 : 1;

        $partner = PartnerModel::where([
            ['shop_id','=',$this->request->shopId],
            ['mobile','=',$member['mobile']],
            ['status','=',1],
            ['is_delete','=',0]
        ])->find();

        $member['is_partner'] =  $partner === null ? 0 : 1;
        $member['partner_role'] = $partner === null ? 0 : $partner->role_id;

        //unset($member['memberlevel']);

        return $this->success($member);

    }
    /*钱包明细*/
    public function getMemberMoneyLogs()

    {
        $date = $this->request->param('date');
        $type= $this->request->param('type/d',0);//0全部1收入2支出3待解冻
        if(empty($date)){
            $date = date('Y-m');
        }
        $start_time = $date.'-01'.' 00:00:00';
        $end_time = date('Y-m-t',strtotime($start_time)).' 23:59:59';

        $where['member_id'] = $this->request->memberId;
        $where['add_start_time'] = $start_time;
        $where['add_end_time'] = $end_time;
        if($type==1) {
            $where['status'] = 1;
            $where['money_status'] = 1;
        }else if($type==2){
            $where['status'] = 0;
        }else if($type==3){
            $where['status'] = 1;
            $where['money_status'] = 0;

        }
        $money_where = [
            ['member_id','=',$this->request->memberId],
            ['add_time','>=',$start_time],
            ['add_time','<=',$end_time],
        ];
        $detail_model = new MemberMoneyDetailModel();
        $return = $detail_model->getList($where,$money_where,['ml.add_time'=>'desc'],$this->request->page,$this->request->limit);

        $member_model = new MemberModel();
        //钱包余额
        $member = $member_model->getById(['member_id'=>$this->request->memberId],'money');
        $return['member_money'] = $member->money;
        //待解冻
        $d_list= $detail_model->getList([],['money_status'=>0,'member_id'=>$this->request->memberId],'');
        $return['wait_money'] = $d_list['income_money'];
        return $this->success($return);

    }
    /*储值卡明细*/
    public function getMemberBalanceLogs()

    {
        $date = $this->request->param('date');
        $type= $this->request->param('type/d',0);//0全部1支出2充值3赠送
        if(empty($date)){
            $date = date('Y-m');
        }
        $start_time = strtotime($date.'-01');
        $end_time = strtotime(date('Y-m-t',strtotime($date.'-01')).' 23:59:59');

        $where = $s_where = $recharge_where =[
            ['member_id','=',$this->request->memberId],
            ['shop_id','=',$this->request->shopId],
            ['add_time','>=',$start_time],
            ['add_time','<=',$end_time],
        ];
        if($type==1) {
            $where[] = ['type','=',-1];
        }
        if($type==2) {
            $where[] = ['type','=',1];
            $where[] = ['type_id','In',[1,2,3,10,12,20]];
        }
        if($type==3) {
            $where[] = ['give_balance','>',0];
        }

        $balance_logs_model = new MemberBalanceLogsModel();

        $order = ['add_time'=>'desc'];

        $field = "type,info,balance,give_balance,add_time";

        $append = ['add_time_format'];

        $return = DataLogic::getDataList($balance_logs_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        $logs_model = new MemberBalanceLogsModel();
        $out_where[] = ['type_id','=',-1];
        $return['out_money'] = $logs_model->statistics($out_where,'balance');
        $recharge_where[] = ['type_id','In',[1,2,3,10,12,20]];
        $return['recharge_money'] = $logs_model->statistics($recharge_where,'balance');
        $return['give_money'] = $logs_model->statistics($where,'give_balance');

        $return['balance'] = MemberBalanceModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$this->request->memberId],
                ['valid_bg_time','<=',$this->request->time()]
            ])->sum('remain_balance') ?? 0;

        $return['total_give_money'] = $logs_model->statistics(['shop_id'=>$this->request->shopId,'member_id'=>$this->request->memberId],'give_balance');

        return $this->success($return);

    }
    /*授权获取手机号*/
    public function mobileAuth() {
        $member=$this->request->member;

        $code = $this->request->param('code');

        $encryptedData = $this->request->param('encryptedData');

        $iv = $this->request->param('iv');

        if(empty($code) || empty($encryptedData) || empty($iv)){

            return $this->error('授权解析失败#01');

        }

        $Openplatform = new OpenPlatformMiniappHelper();

        $this->request->shopId = 35;

        $datas = $Openplatform->setShopId($this->request->shopId)->getUserInfo([

            'code'          => $code,

            'encryptedData' => $encryptedData,

            'iv'            => $iv,

        ]);
        if (false === $datas) {

            return $this->error('授权解析失败');

        }

        MemberModel::where(['member_id'=>$member->member_id])->save(['mobile'=>$datas['mobile']]);

        return $this->success('绑定成功');

    }
    public function getMobile(){
        $member=$this->request->member;
        $return['mobile'] = $member->mobile;
        return $this->success($return);
    }
    //门店是否开启白名单，当前用户是否在该门店白名单
    public function info(){
        //当前门店是否开启白名单
        $shop_detail=ShopDetailModel::find($this->request->shopId);
        $return['white_list_open'] = (!empty($shop_detail) && $shop_detail->white_list_open==1)?1:0;

        $w_list = WhiteListModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>1,'member_id'=>$this->request->memberId])
            ->whereTime('start_time','<=',date('Y-m-d H:i:s'))
            ->whereTime('end_time','>=',date('Y-m-d H:i:s'))
            ->find();

        $return['in_white_list'] = !empty($w_list)?1:0;

        return $this->success($return);
    }
    public function promotion_list(){
        $member=$this->request->member;
        $limit=$this->request->limit;
        $page=$this->request->page;
        $where=[];
        $order['a.id']='desc';
        $where['member_id']=$member->member_id;
        $res_data=PromotionmemberModel::list($where,$order,$page,$limit);
        return $this->success($res_data);
    }
    public function member_info(){
        $member_num = $this->request->param('member_num',null);
        if(empty($member_num)) return $this->error('参数错误');
        $s[]=['member_num','=',$member_num];
        $s[]=['is_delete','=',0];
        $member=MemberModel::where($s)->find();
        if(empty($member)) return $this->error('用户不存在');
        return $this->success($member);
    }
}

